package com.small.nacos.core.cluster.lookup;

import com.alibaba.nacos.common.utils.StringUtils;
import com.small.nacos.common.notify.DefaultPublisher;
import com.small.nacos.core.cluster.AbstractMemberLookup;
import com.small.nacos.core.cluster.Member;
import com.small.nacos.core.cluster.MemberUtil;
import com.small.nacos.sys.env.EnvUtil;
import com.small.nacos.sys.file.FileChangeEvent;
import com.small.nacos.sys.file.FileWatcher;
import com.small.nacos.sys.file.WatchFileCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author zhoujin
 * @Date 2022/11/9 15:28
 */
public class FileConfigMemberLookup extends AbstractMemberLookup {

    protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultPublisher.class);

    private FileWatcher watcher = new FileWatcher() {
        @Override
        public void onChange(FileChangeEvent event) {
            readClusterConfFromDisk();
        }

        @Override
        public boolean interest(String context) {
            return StringUtils.contains(context, "cluster.conf");
        }
    };

    @Override
    protected void doStart() {
        readClusterConfFromDisk();

        try {
            WatchFileCenter.registerWatcher(EnvUtil.getConfPath(), watcher);
        } catch (Throwable e) {
            LOGGER.error("An exception occurred in the launch file monitor : {}", e.getMessage());
        }
    }

    private void readClusterConfFromDisk() {
        // 1. 读取{nacos.home}/conf/cluster.conf，加载tmpMembers
        Collection<Member> tmpMembers = new ArrayList<>();
        try {
            List<String> tmp = EnvUtil.readClusterConf();
            tmpMembers = MemberUtil.readServerConf(tmp);
        } catch (Throwable e) {
            LOGGER
                    .error("nacos-XXXX [serverlist] failed to get serverlist from disk!, error : {}", e.getMessage());
        }
        // 2. 合并服务成员
        afterLookup(tmpMembers);
    }
}
